package com.sso.servlet;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainServlet extends HttpServlet {

    private final String TICKET_KEY = "Ticket_Granting_Ticket";
    private String domains;
    private String ticket;
    private ExecutorService service;

    @Override
    protected void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String servletPath = request.getServletPath();
        if ("/main".equals(servletPath)) {
            domains = request.getParameter("domains");
            ticket = request.getParameter("ticket");
            // 给其他的域名设置同样的 ticket cookie
            for (String server : domains.split(",")) {
                if (Objects.equals(null, server) && Objects.equals("", server)) {
                    setCookie(server, ticket);
                }
            }
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        } else if (Objects.equals("/setCookie", servletPath)) {
            String ticket = request.getParameter("ticket");
            response.addCookie(new Cookie(TICKET_KEY, ticket));
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/text; charset=utf-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.write("ok");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        }
    }

    // 设置 cookie
    public void setCookie (String server, String ticket) {
        // 创建一个有十个线程的线程池
        service = Executors.newFixedThreadPool(10);
        // submit 方法的作用是向线程池提交一个 Runnable 任务用于执行
        service.submit(new Runnable() {
            @Override
            public void run () {
                HttpPost httpPost = new HttpPost(server + "/setCookie?ticket=" + ticket);
                CloseableHttpClient httpClient = null;
                CloseableHttpResponse httpResponse = null;
                try {
                    httpClient = HttpClients.createDefault();
                    httpResponse = httpClient.execute(httpPost);
                    // 此处的 entity 就是添加 cookie 的同时存放到 response 中的 ok，得到 ok 就说明 cookie 添加成功了
                    HttpEntity entity = httpResponse.getEntity();
                    String responseContext = EntityUtils.toString(entity, "UTF-8");
                    System.out.println("responseContext ======================== " + responseContext);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (httpResponse != null) {
                        try {
                            httpResponse.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    if (httpClient != null) {
                        try {
                            httpClient.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
    }

}
